var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var config = require('./config');
var env = process.env.NODE_ENV || 'local';
var router = express.Router();
var Request = require("./apiModules/request");
const $request = new Request();

router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());

//文件上传
var formidable = require('formidable');
var fs = require('fs');
// 初始化Client
var co = require('co');
var oss = require('ali-oss');

const { ContainerClient, BlobServiceClient } = require('@azure/storage-blob');

let blobServiceClient;

if (env.indexOf('hk') > -1) {
  blobServiceClient = BlobServiceClient.fromConnectionString(config.azureConnectingString);
}

var client = oss({
  accessKeyId: 'LTAIN518kPDaZ3z6',
  accessKeySecret: 'Bd1CrVlooF0UkWQwzOcmJw6jsdEVHy',
  bucket: config.ossBucket,
  region: 'oss-cn-hangzhou',
  internal: env === 'local' ? false : true, //内网 或 外网 --本地开发环境下为false，反之为true
  secure: true //https or http
});

const whiteList = [
  "jpg",
  "jpeg",
  "png",
  "gif",
  'bmp',
  "pdf",
  "doc",
  "docx",
  "xls",
  "xlsx",
  "ppt",
  "pptx",
  "msg"
];

let containerName = 'bdhdocuments';    //  azure: 容器名  ali: 根文件夹
const documentModule = ['bi'];   //  存储模块名


//  containerName的名字只能是小写
async function saveFileToAzure(containerName, savePath, filePath, fileName) {
  let containerClient = new ContainerClient(config.azureConnectingString, containerName)
  const isExist = await containerClient.exists();

  if (!isExist) {
    containerClient = blobServiceClient.getContainerClient(containerName);
    await containerClient.create({ access: 'blob' });
  }

  const blockBlobClient = containerClient.getBlockBlobClient(savePath);

  return new Promise(async (resolve, reject) => {
    try {
      console.log('开始上传===>' + filePath);
      let uploadBlobResponse = await blockBlobClient.uploadFile(filePath, { blobHTTPHeaders: { blobContentType: '*/*' } });
      console.log('上传成功===>' + containerClient.url + '/' + savePath)

      const imgInfo = {
        imageUrl: containerClient.url + '/' + savePath,
        name: fileName
      };
      resolve(imgInfo);
    } catch (e) {
      reject({ err: '上传失败', message: e });
    }
    fs.unlinkSync(filePath);
  })
}

function deleteAzureBlob(containerName, blobName) {
  return new Promise(async (resolve, reject) => {
    try {
      const containerClient = blobServiceClient.getContainerClient(containerName);
      let result = await containerClient.deleteBlob(blobName);
      resolve({ 'success': result });
    } catch (e) {
      reject(e)
    }
  })
}

function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
function isLegalFile(fileName) {
  const type = fileName.split(".")[fileName.split(".").length - 1].toLowerCase();
  if (whiteList.indexOf(type) > -1) {
    return true;
  }
  return false;
}

//  保存上传失败的文件
function saveFailFile(oldPath, newfileName) {
  console.log('======上传附件失败=======')
  console.log(oldPath)
  console.log(newfileName)
  fs.copyFileSync(
    oldPath,
    path.resolve(__dirname, './../public/failFile/' + newfileName)
  )
}

//  上传文件
function saveImg(authPath, fileName, file, failName) {
  return new Promise(async (resolve, reject) => {
    try {
      const result = await client.put(authPath, file);
      await client.putACL(authPath, 'public-read'); //设置该图片可访问权限
      if (result.res && result.res.status === 200) {
        const imgInfo = {
          imageUrl: result.url.replace('-internal', ''),
          name: fileName
        };
        // 上传成功删除临时文件
        fs.unlinkSync(file);
        resolve(imgInfo);
      } else {
        failName && saveFailFile(file, failName)
        reject({ err: '上传失败' });
      }

    } catch (e) {
      failName && saveFailFile(file, failName)
      reject({ err: '上传失败' });
    }

  })
}
router.post('/', async function (req, res, next) {
  res.set({ 'Content-Type': 'application/json;charset=utf-8' });

  let tenantId = req.headers.user.tenantId;
  let organizationId = req.headers.user.organizationId;
  let userId = req.headers.user.userId;
  console.log(req.headers.user, 'user======>');
  var form = new formidable.IncomingForm();
  form.uploadDir = path.resolve(__dirname + "./../public/tmp");
  form.keepExtensions = true;//保留后缀
  form.maxFieldsSize = 10 * 1024 * 1024;
  form.encoding = 'utf-8';

  const fileList = [];
  form.on('file', function (filed, file) {
    fileList.push(file);//收集传过来的所有文件
  }).parse(req, async function (err, fields, files) {

    if (fileList.some(v => !isLegalFile(v.name))) {
      return res.json({ status: 101, message: "上传文件格式错误", error: '' });
    }

    let tenantCode = req.headers.user.tenantCode;     //  租户code
    let moduleName = fields.moduleName || '';         //  模块名： iexpense, scm, vacation....

    let promiseArray = [];
    fileList.map((file) => {
      let ossFileName = '';
      let AzureContainerName = '';
      let savePath = '';

      if (moduleName && documentModule.includes(moduleName)) {
        let pageId = fields.pageId;
        let imageChartId = fields.imageChartId;
        savePath = `${tenantCode}/${moduleName}/${pageId}/${imageChartId}/${file.name}`;
      } else {
        savePath = `${tenantCode}/other/${file.name}`;
      }

      let newUploadPromise;
      if (env.indexOf('hk') > -1) {
        //  azure上传
        newUploadPromise = saveFileToAzure(containerName, savePath, file.path, file.name, savePath.replace(/\//g, '_'));
      } else {
        //  阿里云上传
        newUploadPromise = saveImg(`${containerName}/${savePath}`, file.name, file.path, savePath.replace(/\//g, '_'));
      }

      promiseArray.push(newUploadPromise);
    });

    Promise.all(promiseArray).then(result => {
      res.end(JSON.stringify({ status: 1, message: 'success', data: result }));
    }, (err) => {
      res.end(JSON.stringify({ status: 101, message: '上传失败', error: err }));
    });

  });
})

router.post('/deleteFile', function (req, res, files) {
  // console.log(req.body);
  // console.log(req.headers);
  // let authInfo = JSON.parse(req.headers.auth);

  // let tenantId = req.headers.user.tenantId;
  // let organizationId = req.headers.user.organizationId;
  let AjaxData = req.body;
  let promise = [];
  for (let item of AjaxData) {
    if (env.indexOf('hk') > -1) {

      const blobName = item.url.split(`${containerName}/`)[1];

      promise.push(deleteAzureBlob(containerName, blobName))

    } else {

      promise.push(new Promise(async function (resolve, reject) {
        try{
          let _path = item.url.replace('https://', '');
          let keys = _path.split("/");
          keys.splice(0, 1);
          let key = keys.join("/");
          var result = await client.delete(key);
          resolve({ 'success': result });
        } catch ( err ) {
          reject(err);
        }
      }));
    }

  }
  Promise.all(promise).then(function (value) {
    // console.log('deleteDone:' + JSON.stringify(value));
    res.end(JSON.stringify({ status: 1, message: 'success' }));
  }, (err) => {
    res.json({ status: 101, message: '删除失败', error: err });
  });
})


module.exports = router;
